//
//  SearchViewController.m
//  FeiYang
//
//  Created by Maxwell Rose on 15/10/16.
//  Copyright © 2015年 feiyang. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchHistoryCell.h"
#import "SearchHintCell.h"
#import "MagazineCollectionModel.h"
#import "MagazineCollectionViewCell.h"
#import "BookPageViewController.h"

//collectionViewCell的高度
#define kCellWidth      ((SCREEN_WIDTH - 16*4 ) / 3.0)
#define kCellHeight     (kCellWidth * 4 / 3.0 + 22)
static NSString *const MagazineCollectionCell = @"MagazineCollectionCell";


typedef NS_ENUM(NSInteger,SeachTableViewMode){
    SeachTableViewModeHistory,
    SeachTableViewModeHint
};
@interface SearchViewController ()<UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, UICollectionViewDataSource, UICollectionViewDelegate>

@property (strong, nonatomic) UITableView *tableView;

@property (strong, nonatomic) UICollectionView *collectionView;

@property (assign, nonatomic) SeachTableViewMode tableMode;

@property (strong, nonatomic) NSMutableArray *historyArray;

@property (strong, nonatomic) NSMutableArray *hintArray;

@property (strong, nonatomic) NSMutableArray *dataSources;

@property (strong, nonatomic) UILabel *noDataView;

@property (strong, nonatomic) UIView *noNet;

@property (strong, nonatomic) UITapGestureRecognizer *tapGesture;



@end

@implementation SearchViewController

- (instancetype)init{
    if (self = [super init]) {
        [self setHidesBottomBarWhenPushed:YES];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.edgesForExtendedLayout = UIRectEdgeNone;

    self.dataSources = [NSMutableArray array];
    self.view.backgroundColor = [UIColor whiteColor];
    [self addSearchView];
    [self setupCollectionView];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"icon_back_thin"] style:(UIBarButtonItemStyleBordered) target:self action:@selector(back)];

//    初始化tableview
    self.historyArray = [self historyArray];
    if (0 != self.historyArray.count) {
        [self swichTableViewMode:SeachTableViewModeHistory];
    }
    [self.view addSubview:self.tableView];
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

/**
 *  切换实时搜索或者历史
 *
 *  @param mode SeachTableViewModeHistory or SeachTableViewModeHint
 */
- (void)swichTableViewMode:(SeachTableViewMode)mode{
    self.tableMode = mode;
    if (mode == SeachTableViewModeHistory) {
        [self addClearHistoryButtonView];
    }else{
        self.tableView.tableHeaderView = nil;
    }
    [self.tableView reloadData];
    [self.view bringSubviewToFront:self.tableView];
}

- (void)addSearchView{
    //    添加搜索框
    UITextField *searchField = [[UITextField alloc]initWithFrame:CGRectMake(44, 26, SCREEN_WIDTH - 44 - 56, 32)];
    searchField.placeholder = @"请输入您要搜索的杂志";
    searchField.delegate = self;
    searchField.borderStyle = UITextBorderStyleNone;
    searchField.font = [UIFont systemFontOfSize:14];
    searchField.backgroundColor = [UIColor whiteColor];
    searchField.textColor = [UIColor colorWithWhite:0.000 alpha:0.300];
    searchField.layer.cornerRadius = 4;
    searchField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [searchField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    searchField.textColor = [UIColor colorWithWhite:0.000 alpha:0.300];
    
    
    UIImageView *leftView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_search"]];
    CGRect rect = leftView.frame;
    rect.origin.x += 5;
    leftView.frame = rect;
    UIView *leftBackgroudView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, leftView.frame.size.width + 5, leftView.frame.size.height)];
    [leftBackgroudView addSubview:leftView];
    
    searchField.leftView = leftBackgroudView;
    searchField.leftViewMode = UITextFieldViewModeAlways;
    self.searchField = searchField;
//    [topView addSubview:searchField];
    self.navigationItem.titleView = self.searchField;
    
    //    添加搜索按钮
    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc]initWithTitle:@"搜索" style:(UIBarButtonItemStylePlain) target:self action:@selector(searchButtonAction:)];
    self.navigationItem.rightBarButtonItem = searchItem;
}

/**
 *  添加清空历史按钮
 */
- (void)addClearHistoryButtonView{
    if (!self.tableView.tableHeaderView) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(SCREEN_WIDTH - 120, 9, 120, 30);
        [button setTitleColor:kColorOrangeMain forState:UIControlStateNormal];
        [button setTitleColor:kColorOrangePressed forState:UIControlStateHighlighted];

        [button setTitle:@"清空历史" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(clearHistory:) forControlEvents:UIControlEventTouchUpInside];
        [button setImage:[UIImage imageNamed:@"search_history_del"] forState:UIControlStateNormal];
        [view addSubview:button];
        
        self.tableView.tableHeaderView = view;
    }
}

/**
 *  懒加载tableview
 *
 *  @return UITableView
 */
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = kColorGrayBackground;
        [_tableView registerClass:[SearchHistoryCell class] forCellReuseIdentifier:@"SearchHistoryCell"];
        [_tableView registerClass:[SearchHintCell class] forCellReuseIdentifier:@"SearchHintCell"];
        
        self.hintArray = [NSMutableArray array];
        self.historyArray = [NSMutableArray array];
        
    }
    return _tableView;
}

- (void)refresh{
    
    self.noDataView.hidden = YES;
    self.noNet.hidden = TRUE;
    
    static NSInteger nextPage = 1;
    if (_dataSources.count == 0) {
        nextPage = 0;
    }
    //发送网络请求获取视频列表
    NSDictionary *parameter = @{@"title":self.searchField.text,
                                @"page.pn":[NSNumber numberWithInteger: nextPage == 0 ? 1 : nextPage]
                                };
    
    [AppGlobalClass PostDataWithNSstring:kLinkOfSearch withDictionary:parameter success:^(NSDictionary *dictionary) {
        NSLog(@" %d | %s | %@",__LINE__,__FUNCTION__,dictionary);
        if ([[dictionary objectForKey:@"success"] isEqualToNumber:@YES])
        {
            NSDictionary *responseDate = [dictionary[@"responseData"] firstObject];
            NSInteger pages = [responseDate[@"pages"] integerValue];
            NSInteger currentPage = [responseDate[@"page"] integerValue];
            NSInteger total = [responseDate[@"total"] integerValue];
            if (pages == 1) {//如果只有一页数据则情况数据，重新加载
                [self.dataSources removeAllObjects];
            }
            NSArray * rowsArray = responseDate[@"rows"];
            for (NSDictionary * dataDict in rowsArray)
            {
                MagazineCollectionModel * model = [[MagazineCollectionModel alloc]init];
                [model setValuesForKeysWithDictionary:dataDict];
                [_dataSources addObject:model];
            }
            
            if (_dataSources.count > 0)
            {
                [_collectionView reloadData];
            }
            else{
                _noDataView.hidden =FALSE;
            }
            
            if (pages > 1) {
                nextPage = currentPage + 1;
                if (pages > currentPage) {//没有到最后一页，继续加载
                    if (total >= 11) {
                        [self refresh];
                    }
                    _collectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                        [self refresh];
                    }];
                }else if (pages == currentPage) {//最后一页
                    [_collectionView.footer endRefreshingWithNoMoreData];
                    nextPage = 1;
                }
                
            }
            
        }else{
            //没有真确返回
            [self.dataSources removeAllObjects];
            [_collectionView reloadData];
            _noDataView.hidden = FALSE;
            
        }
        [self.collectionView.header endRefreshing];
        
    } failure:^(NSError *error) {
        NSLog(@"----%@",error);
        _noDataView.hidden = FALSE;
        [_dataSources removeAllObjects];
        [_collectionView reloadData];
        [self.collectionView.header endRefreshing];
        [_collectionView.footer setState:MJRefreshStateIdle];
        [_collectionView.footer endRefreshing];
        
    } networkerror:^(NSString *networkerror) {
        NSLog(@"----");
        _noNet.hidden = FALSE;
        
        [_dataSources removeAllObjects];
        [_collectionView reloadData];
        
        [self.collectionView.header endRefreshing];
        [_collectionView.footer setState:MJRefreshStateIdle];
        [_collectionView.footer endRefreshing];
        
    }];
    
}

#pragma mark - UICollectionViewController 初始化
- (UICollectionView *)collectionView{
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
        [self.view addSubview: _collectionView];
        [_collectionView addSubview:self.noNet];
        [_collectionView addSubview:self.noDataView];
    }
    return _collectionView;
}

/**
 *  设置CollectionView
 */
- (void)setupCollectionView{
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background（750）"]];

    [_collectionView registerNib:[UINib nibWithNibName:@"MagazineCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:MagazineCollectionCell];
    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [_dataSources removeAllObjects];
        [_collectionView reloadData];
        [self refresh];
    }];
}

#pragma mark - UI交互处理
- (void)searchButtonAction:(UIButton *)btn{
    [self.view bringSubviewToFront:self.collectionView];
    NSMutableArray *history = [self historyArray];
    if (![history containsObject:self.searchField.text]) {
        //历史中不含此搜索字符
        if (![self.searchField.text isEqualToString:@""]) {
            [history insertObject:self.searchField.text atIndex:0];
        }
    }else{
        //包含
        [history exchangeObjectAtIndex:0 withObjectAtIndex:[history indexOfObject:self.searchField.text]];
    }
    
    NSLog(@" %d | %s | %@",__LINE__,__FUNCTION__,history);
    [[NSUserDefaults standardUserDefaults] setObject:history forKey:@"searchHistroyArray"];
    [self.collectionView.header beginRefreshing];
    [self.searchField resignFirstResponder];
    
    //    [self refresh];
}

- (void)backButtonAction:(UIButton *)btn{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if (!_tapGesture) {
        _tapGesture = [[UITapGestureRecognizer alloc]init];
        [_tapGesture addTarget:self action:@selector(resignKeyBoard)];
    }
    [self.view addGestureRecognizer:_tapGesture];
    NSLog(@" %d | %s ",__LINE__,__FUNCTION__);
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    [self.view removeGestureRecognizer:_tapGesture];
}

// called when 'return' key pressed. return NO to ignore.
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.searchField resignFirstResponder];
    [self searchButtonAction:nil];
    return YES;
    
}

- (void)textFieldDidChange:(UITextField *) TextField{
    if (0 == TextField.text.length) {
        [self swichTableViewMode:SeachTableViewModeHistory];
    }else{
        [self swichTableViewMode:SeachTableViewModeHistory];
        //        暂时无模糊搜索提示
        //        [self.hintArray addObject:TextField.text];
        //        [self swichTableViewMode:SeachTableViewModeHint];
    }
}

- (void)clearHistory:(UIButton *)btn{
    [self saveHistoryArray:[NSArray array]];
    [self.tableView reloadData];
}

- (void)noResultButtonAction:(UIButton *)btn{
    [self.collectionView.header beginRefreshing];
}

- (void)resignKeyBoard{
    [self.searchField resignFirstResponder];
}
#pragma mark - 数据持久化
/**
 *  获取存储的历史搜索记录
 *
 *  @return 包含历史搜索记录的可变数组
 */
- (NSMutableArray *)historyArray{
    NSMutableArray *history = [(NSMutableArray *)[[NSUserDefaults standardUserDefaults] objectForKey:@"searchHistroyArray"] mutableCopy];
    if (!history) {
        history = [NSMutableArray array];
    }
    return history;
}

/**
 *  存储搜索记录
 *
 *  @param historyArray 包含记录的数组
 */
- (void)saveHistoryArray:(NSArray *)historyArray{
    [[NSUserDefaults standardUserDefaults] setObject:historyArray forKey:@"searchHistroyArray"];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.tableMode == SeachTableViewModeHistory) {
        return self.historyArray.count;
    }else{
        //SeachTableViewModeHint
        return self.hintArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.tableMode == SeachTableViewModeHistory) {
        SearchHistoryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchHistoryCell" forIndexPath:indexPath];
        cell.textLabel.text = self.historyArray[indexPath.row];
        return cell;

    }else{
        //SeachTableViewModeHint
        SearchHintCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchHintCell" forIndexPath:indexPath];
        cell.textLabel.text = self.hintArray[indexPath.row];
        return cell;

    }

}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 48;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.tableMode == SeachTableViewModeHistory) {
        self.searchField.text = self.historyArray[indexPath.row];
        
    }else{
        //SeachTableViewModeHint
        self.searchField.text = self.hintArray[indexPath.row];
    }
}

#pragma mark - <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataSources.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    MagazineCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:MagazineCollectionCell forIndexPath:indexPath];
    MagazineCollectionModel * model = _dataSources[indexPath.row];
    cell.model = model;
    return cell;
}

#pragma mark - UICollection View Delegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    MagazineCollectionModel *model = _dataSources[indexPath.row];
    
    BookPageViewController *bookPageViewCon = [[BookPageViewController alloc]initWithBookID:model.ebookId];
    bookPageViewCon.title = model.title;
    [self.navigationController pushViewController:bookPageViewCon animated:TRUE];
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    
}


#pragma mark - UICollection View Delegate FlowLayout
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 15;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 15;
}

//定义每个UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(16, 16, 16, 16);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(kCellWidth, kCellHeight);
}

//没网提示
#pragma mark - 无网提示
-(UIView *)noNet
{
    if (!_noNet) {
        _noNet = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 235)];
        _noNet.center = CGPointMake(_collectionView.center.x, _collectionView.center.y - 64 - 32);
        _noNet.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 200, 200);
        [button setImage:[UIImage imageNamed:@"img_nonetwork"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 40, 200, 44)];
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        NSMutableAttributedString *aString = [[NSMutableAttributedString alloc]initWithString:@"加载失败\n请检查手机是否联网"];
        
        [aString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17],
                                 NSForegroundColorAttributeName:[UIColor colorWithWhite:0.098 alpha:1.000],
                                 } range:NSMakeRange(0, 5)];
        
        [aString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12],
                                 NSForegroundColorAttributeName:[UIColor colorWithWhite:0.702 alpha:1.000],
                                 } range:NSMakeRange(5, 9)];
        [label setAttributedText:aString];
        [_noNet addSubview:label];
        [_noNet addSubview:button];
        
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame = CGRectMake(60, 210, 80, 25);
        btn.backgroundColor = [UIColor colorWithWhite:0.200 alpha:1.000];
        btn.layer.cornerRadius = 6;
        btn.layer.masksToBounds = YES;
        [btn setTitle:@"重新加载" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_noNet addSubview:btn];
    }
    return _noNet;
}
-(UILabel *)noDataView
{
    if (!_noDataView) {
        _noDataView = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 20.f, SCREEN_WIDTH, 24.0f)];
        _noDataView.text = @"未搜到相关结果";
        _noDataView.hidden = TRUE;
        _noDataView.textAlignment = NSTextAlignmentCenter;
        _noDataView.textColor = [UIColor colorWithWhite:0.000 alpha:0.540];
    }
    return _noDataView;
}


@end
